import { uploadImage } from '@/apis/uploadApi';

export default class {
  editor: toastui.Editor;
  isFullscreen: boolean;
  constructor(el: string, public height: string, initialValue?: string) {
    this.editor = new toastui.Editor({
      el: document.querySelector(el),
      height,
      initialEditType: 'markdown',
      previewStyle: 'vertical',
      initialValue,
      toolbarItems: this.getToolBars()
    });
    this.isFullscreen = false;
    this.ImageHook();
  }
  // 获取工具栏
  private getToolBars() {
    return [
      ['heading', 'bold', 'italic', 'strike'],
      ['hr', 'quote'],
      ['ul', 'ol', 'task', 'indent', 'outdent'],
      ['table', 'image', 'link'],
      ['code'],
      [
        {
          el: this.fullScreen(),
          command: 'fullScreen',
          tooltip: 'fullScreen'
        }
      ]
    ];
  }
  // 全屏事件
  private fullScreen() {
    const btn = document.createElement('button') as HTMLButtonElement;
    btn.innerHTML = '全屏';
    btn.style.margin = '0';
    this.handleFullscreen(btn);
    this.handleKeyupEsc();
    return btn;
  }
  // 监听全屏点击事件
  private handleFullscreen(btn: HTMLButtonElement) {
    btn.addEventListener('click', () => {
      this.setHeight('100vh');
      const ui = this.getToastElement();
      ui.classList.toggle('fullscreen');
      this.isFullscreen = !this.isFullscreen;
      this.editor.focus();
      if (this.isFullscreen === false) {
        this.setHeight(this.height);
      }
    });
  }
  // 监听esc事件
  private handleKeyupEsc() {
    document.documentElement.addEventListener('keyup', (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        const ui = this.getToastElement();
        ui.classList.remove('fullscreen');
        this.editor.focus();
        this.isFullscreen = false;
        this.setHeight(this.height);
      }
    });
  }
  // 获取富文本编辑器
  private getToastElement(): HTMLDivElement {
    return document.querySelector('.toastui-editor-defaultUI') as HTMLDivElement;
  }
  // 调整高度
  private setHeight(height: string) {
    this.editor.setHeight(height);
  }
  // 图片上传
  private ImageHook() {
    // 移除默认钩子
    this.editor.removeHook('addImageBlobHook');

    // 添加钩子
    this.editor.addHook('addImageBlobHook', async (blob: any, callback: Function) => {
      const form = new FormData();
      form.append('file', blob, blob.name);
      const resp = await uploadImage(form);
      callback(resp.result.url, blob.name);
    });
  }
}
